package gateway.route;


import cn.hutool.crypto.digest.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class RouteFileListener implements ApplicationRunner , ApplicationContextAware {
    private String routeFileMd5;

    private static ApplicationContext context;

    private static final MD5 md5 = MD5.create();

    @Value("${routes.file}")
    String routeFile;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
        routeFileMd5  = md5.digestHex16(new File(routeFile));
    }

    @Override
    public void run(ApplicationArguments args) {
        Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(()->{
            String newMd5 = md5.digestHex16(new File(routeFile));
            log.info("old:{},new:{}",routeFileMd5,newMd5);
            if(!routeFileMd5.equals(newMd5 )){
                log.info("路由文件发生变更");
                routeFileMd5 = newMd5;
                context.publishEvent(new RefreshRoutesEvent(this));
            }

        },5, 5,TimeUnit.SECONDS);
    }
}
